#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
强制缩容脚本
直接销毁多余的服务器，保留最小数量
"""

import requests
import time
import json

def force_scale_in():
    """强制缩容"""
    base_url = "http://localhost:8080"
    
    print("🗑️  强制缩容脚本")
    print("=" * 50)
    
    # 1. 获取所有服务器列表
    print("📊 获取服务器列表...")
    try:
        servers_response = requests.get(f"{base_url}/api/v1/servers", timeout=10)
        if servers_response.status_code == 200:
            servers_data = servers_response.json()
            if servers_data.get("success"):
                servers_list = servers_data["data"]
                total_servers = len(servers_list)
                print(f"  发现 {total_servers} 个服务器")
                
                # 获取最小服务器数量配置
                status_response = requests.get(f"{base_url}/api/v1/system/status", timeout=10)
                if status_response.status_code == 200:
                    status_data = status_response.json()
                    min_servers = status_data["data"]["scaling"]["scaling_config"]["min_servers"]
                    print(f"  最小服务器数量: {min_servers}")
                    
                    if total_servers <= min_servers:
                        print("✅ 当前服务器数量已达到最小值，无需缩容")
                        return
                    
                    # 计算需要销毁的服务器数量
                    servers_to_destroy = total_servers - min_servers
                    print(f"  需要销毁 {servers_to_destroy} 个服务器")
                    
                    # 显示所有服务器
                    print(f"\n📋 当前服务器列表:")
                    for i, server in enumerate(servers_list):
                        print(f"  {i+1}. {server['instance_id']} - {server['status']} - CPU: {server['cpu_usage']:.1f}%")
                    
                    # 选择要销毁的服务器（保留前min_servers个，销毁其余的）
                    servers_to_keep = servers_list[:min_servers]
                    servers_to_destroy_list = servers_list[min_servers:]
                    
                    print(f"\n✅ 将保留的服务器:")
                    for i, server in enumerate(servers_to_keep):
                        print(f"  {i+1}. {server['instance_id']}")
                    
                    print(f"\n🗑️  将销毁的服务器:")
                    for i, server in enumerate(servers_to_destroy_list):
                        print(f"  {i+1}. {server['instance_id']}")
                    
                    # 确认操作
                    print(f"\n⚠️  警告：这将销毁 {len(servers_to_destroy_list)} 个服务器！")
                    print("按 Ctrl+C 取消，或等待5秒后自动开始...")
                    
                    try:
                        time.sleep(5)
                    except KeyboardInterrupt:
                        print("\n❌ 操作已取消")
                        return
                    
                    # 开始销毁服务器
                    print(f"\n🚀 开始销毁服务器...")
                    success_count = 0
                    fail_count = 0
                    
                    for i, server in enumerate(servers_to_destroy_list):
                        server_id = server["instance_id"]
                        print(f"  正在销毁服务器 {i+1}/{len(servers_to_destroy_list)}: {server_id}")
                        
                        try:
                            destroy_response = requests.delete(f"{base_url}/api/v1/servers/{server_id}", timeout=30)
                            if destroy_response.status_code == 200:
                                result = destroy_response.json()
                                if result.get("success"):
                                    print(f"    ✅ 销毁成功: {server_id}")
                                    success_count += 1
                                else:
                                    print(f"    ❌ 销毁失败: {result.get('error')}")
                                    fail_count += 1
                            else:
                                print(f"    ❌ 销毁请求失败: {destroy_response.status_code}")
                                fail_count += 1
                        except Exception as e:
                            print(f"    ❌ 销毁异常: {e}")
                            fail_count += 1
                        
                        time.sleep(3)  # 等待销毁完成
                    
                    print(f"\n🎉 销毁操作完成！")
                    print(f"  ✅ 成功销毁: {success_count} 个")
                    print(f"  ❌ 销毁失败: {fail_count} 个")
                    
                    # 等待一段时间后检查最终状态
                    print(f"\n⏳ 等待5秒后检查最终状态...")
                    time.sleep(5)
                    
                    try:
                        final_response = requests.get(f"{base_url}/api/v1/servers", timeout=10)
                        if final_response.status_code == 200:
                            final_data = final_response.json()
                            if final_data.get("success"):
                                final_servers = final_data["data"]
                                print(f"📊 最终状态: 剩余 {len(final_servers)} 个服务器")
                                for server in final_servers:
                                    print(f"  - {server['instance_id']} ({server['status']})")
                        else:
                            print(f"❌ 获取最终状态失败: {final_response.status_code}")
                    except Exception as e:
                        print(f"❌ 获取最终状态异常: {e}")
                        
                else:
                    print(f"❌ 获取系统状态失败: {status_response.status_code}")
            else:
                print(f"❌ 获取服务器列表失败: {servers_data.get('error')}")
        else:
            print(f"❌ 获取服务器列表请求失败: {servers_response.status_code}")
    except Exception as e:
        print(f"❌ 请求失败: {e}")

if __name__ == "__main__":
    force_scale_in()
